package reflection;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @Author Corday 天涯
 * @Date 2022/3/16 16:39
 * 创建一个实体类，运用反射技术获取它的相关信息
 * 比如：类名，方法名，方法中的参数，注解信息等
 */
public class Parrot {
    @MyAnn(descibe ="名称",type =String.class,value = "小五")
    private String name;
    @MyAnn(descibe ="颜色",type =String.class,value = "白色")
    private String color;
    @MyAnn(descibe ="颜值",type =int.class,value = "100")
    private int face;

    public Parrot() {
    }

    public Parrot(String name, String color, @MyAnn(descibe ="颜值",type = int.class,value = "99") int face) {
        this.name = name;
        this.color = color;
        this.face = face;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getFace() {
        return face;
    }

    public void setFace(int face) {
        this.face = face;
    }

    @Override
    public String toString() {
        return "(" + this.name + ":" + this.color + ":" + this.face + ")";
    }
}

//测试一下
class TestParrot {
    public static void main(String[] args) {
        play();
    }//main

    public static void play() {
//        运用反射技术获取对象的信息
        Parrot parrot = new Parrot("小红", "红色", 99);
        Class c = parrot.getClass();
//       1.通过反射获取声明的构造器信息
        Constructor[] constructors = c.getDeclaredConstructors();
        System.out.println("---1.反射获取构造---");
        for (Constructor temp : constructors) {
            System.out.println("构造名:" + temp.getName() + " 参数个数：" + temp.getParameterCount());
            Parameter[] ps = temp.getParameters();
            for (Parameter p : ps) {
                System.out.println("名称：" + p.getName() + " 类型：" + p.getType());
            }
//2.通过反射获取声明的字段（属性）
            Field[] fields = c.getDeclaredFields();
// 3.通过反射获取声明的方法
            Method[] methods = c.getDeclaredMethods();
// 4.通过反射获取声明的注解
            Annotation[] anns = c.getDeclaredAnnotations();
        }
 //5.获取自定义注解的信息
        System.out.println("---5.通过反射获取自定义注解---");
        //Class cc = parrot.getClass();
        Class cc = null;
        try {
            //直接通过类名创建类对象
            cc = Class.forName("reflection.Parrot");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Field[] fields = cc.getDeclaredFields();
        for(Field temp:fields){
           Annotation[] anns=temp.getDeclaredAnnotations();
           for(Annotation a:anns){
               MyAnn myAnn=(MyAnn)a;
               System.out.println("描述："+myAnn.descibe()+" 值："+myAnn.value());
           }//for
        }
    }
}
